package cilent;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) {
        new Client().open();
    }

    private Socket socket;

    //打开浏览器
    //输入url
    public void open(){
        System.out.println("=====打开浏览器===== =");
        System.out.println("URL:");
        Scanner input = new Scanner(System.in);
        String url = input.nextLine();
        this.parseURL(url);
    }

    //解析url
    private void parseURL(String url){
        int index1 = url.indexOf(":");//第一次冒号的位置
        int index2 = url.indexOf("/");//第一次斜杠的位置
        String ip = url.substring(0, index1);
        int port = Integer.parseInt(url.substring(index1 + 1, index2));
        String content = url.substring(index2 + 1);
        this.createSocketAndSendRequest(ip,port,content);
    }

    //创建链接
    //发送请求
    private void createSocketAndSendRequest(String ip,int port,String content){
        try {
            //创建链接
            socket = new Socket(ip,port);
            //发送链接
            //获取一个输出流
            OutputStream outputStream = socket.getOutputStream();
            //如果利用上面的字节流输出流，遇见中文可能会不方便
            //所以将字节流，包装成一个字符流
            PrintStream writer = new PrintStream(outputStream);//装饰者模式
            writer.println(content);
            writer.flush();
            //等着服务器响应回来
            receiveResponse();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void receiveResponse(){
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String responseContent = reader.readLine();
            this.parseResponseContent(responseContent);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void parseResponseContent(String responseContent){
        int index1 = responseContent.indexOf("<");
        int index2 = responseContent.indexOf(">");
        if (index1 != -1 && index2 != -1 && index1 < index2){
            String key = responseContent.substring(index1 + 1,index2);
            if (key.equals("br")){
                responseContent = responseContent.replace("<br>","\r\n");
            }
        }
        System.out.println(responseContent);
    }
}
